﻿/*   
    Copyright (C) 2009 Galaktika Corporation ZAO

    This file is a part of Galaktika.BusinessMonitor
 
    Galaktika.BusinessMonitor is a free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
      
    You should have received a copy of the GNU General Public License
    along with Galaktika.BusinessMonitor.  If not, see <http://www.gnu.org/licenses/>.
  
    If GPL v.3 is not suitable for your products or company,
    Galaktika Corp provides Galaktika.BusinessMonitor under a flexible commercial license
    designed to meet your specific usage and distribution requirements.
    If you have already obtained a commercial license from Galaktika Corp,
    you can use this file under those license terms.
*/

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.IO;
using System.Security.Principal;
using System.Web;

namespace Galaktika.BI.Silverlight.ClientApp.Web.IO
{
    using Galaktika.BI.Silverlight.ClientApp.Web.DAL;

    public class UserSettingsFileSystemStorage : IAppSettingStorage
    {
        public UserSettingsFileSystemStorage()
        {
        }

        #region IAppSettingStorage Members

        public string LoadSettings(IPrincipal currentPrincipal)
        {
            string folder = string.Empty;
            if (this.GetFolderForPrincipal(currentPrincipal, ref folder))
            {
                string path = Path.Combine(folder, Consts.UserSettingsFileName);
                if (File.Exists(path))
                {
                    using (StreamReader sr = new StreamReader(File.Open(path, FileMode.Open, FileAccess.Read)))
                    {
                        return sr.ReadToEnd();
                    }
                }
            }

            return null;
        }

        public void SaveSettings(IPrincipal currentPrincipal, string settingsStr)
        {
            //UserSettings settings = XmlUtility.XmlStr2Obj<UserSettings>(settingsStr);
            string folder = string.Empty;
            if (this.GetFolderForPrincipal(currentPrincipal, ref folder))
            {
                string path = Path.Combine(folder, Consts.UserSettingsFileName);

                //var merger = new SettingsMerger(settings);
                //if (File.Exists(path))
                //{
                //    using (var sr = new StreamReader(File.OpenRead(path)))
                //    {
                //        var list = XmlUtility.XmlStr2Obj<UserSettings>(sr);
                //        merger.Merge(list.Variables);
                //    }
                //}
                //merger.Merge(settings.Variables);
                //if (File.Exists(path))
                //{
                //    File.Delete(path);
                //}
                using (var sw = new StreamWriter(File.OpenWrite(path)))
                {
                    //sw.Write(XmlUtility.Obj2XmlStr(merger.GetSettings()));
                    sw.Write(settingsStr);
                }
            }
        }

        public DateTime GetLastModifiedTime(IPrincipal currentPrincipal)
        {
            string folder = string.Empty;
            if (this.GetFolderForPrincipal(currentPrincipal, ref folder))
            {
                string path = Path.Combine(folder, Consts.UserSettingsFileName);
                if (File.Exists(path))
                {
                    return DateTimeHelper.GetLastWriteTime(path);
                }
            }

            return DateTime.MinValue;
        }

        private bool GetFolderForPrincipal(IPrincipal principal, ref string folder)
        {
            bool res = false;
            string name = string.Empty;
            if (principal == null || principal.Identity == null ||
                string.IsNullOrEmpty(principal.Identity.Name))
            {
                //return res;
                name = "SYSTEM";
            }
            else
            {
                name = principal.Identity.Name;
            }

            //try
            //{
                string path = Path.Combine(this.UserStorageBase, name);//.Replace(Path.PathSeparator, ','));
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                folder = path;
                res = true;
            //}
            //catch (IOException)
            //{
            //}
            //catch (UnauthorizedAccessException)
            //{
            //}

            return res;
        }

        private string UserStorageBase
        {
            get
            {
                string path = ConfigurationManager.AppSettings["UserStoragePath"];
                if (string.IsNullOrEmpty(path))
                {
                    path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UserStorage");
                }
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                return path;
            }
        }

        #endregion
    }
}
